<?php
/**
 * Created by PhpStorm.
 * User: minicart
 * Date: 2018/11/3
 * Time: 11:54
 */
namespace app\admin\service;
use app\models\ContractModificationModel;
use app\models\ContractModel;
use app\models\CourseContractModel;
use app\models\CourseLogModel;
use app\models\CourseModel;
use app\models\ReceivablesModel;

/**
 * Class ContractService
 * @package app\admin\service
 */
class ContractService
{
    /**
     * 已签约客户
     * @return array
     */
    public function contract_management()
    {
        try {
            $page = input('page',1);
            $listRows = input('limit',5);
            $campus = input('campus','');
            $grade = input('grade','');
            $student_name = input('student_name','');
            $signing_date = input('signing_date','');
            $where = [];
            if($campus) $where['campus'] = $campus;
            if($grade) $where['grade'] = $grade;
            if($student_name) $where['student_name'] = ['like','%'.$student_name.'%'] ;
            if($signing_date)$where['signing_date'] = $signing_date;
            $type = input('type','all');
            $order = 'status desc';
            if($type == 'all'){
                $where['status'] = ['in','1,2'];
            }else if($type == 'stay'){
                $where['status'] = 2;
            }
            return $customers = ContractModel::pageLists($where, $page,$listRows, $order);
        } catch (\Exception $ex) {
            return ['code' => 1, 'msg' => $ex->getMessage()];
        }
    }

    /**
     * @param $type
     * @return array
     */
    public function logic($type)
    {
        try {
            $user = session('user');
            $data = input('post.');

            $CourseModel = new CourseModel();


            //插入订单修改记录表
            $contract_front = ContractModel::get(['id'=> $data['id']]);
            $course_id_str = $contract_front['course'];
            $key_value = array(
                "id" => "订单编号自增ID",
                "contract_number" => "订单编号",
                "student_id" => "学生自增ID",
                "student_name" => "学生姓名",
                "grade" => "学员年级",
                "class" => "班级",
                "signing_date" => "签约日期",
                "campus_id" => "签约校区",
                "contractor" => "签约人",
                "contract_type" => "订单类型",
                "signing_type" => "签约类型",
                "total_amount" => "应收金额",
                "preferential" => "优惠金额",
                "amount" => "课程收费",
                "stay_amount" => "欠费金额",
                "direct_discount" => "直减优惠",
                "discount_rate" => "折扣比率",
                "discount_modle" => "优惠方案",
                "integrals" => "积分",
                "stay_distributed" => "待分配金额",
                "course" => "课程",
                "package" => "课程包",
                "in_remark" => "对内备注",
                "out_remark" => "对外备注",
                "status" => "订单状态STATUS",
                "create_time" => "创建时间",
                "update_time" => "更新时间"
            );


            /******应收金额*****/
            $data['total_amount'] = ($data['total_amount'] - $data['preferential']);  //应收金额

            if($type == 2){

                /**2018-12-03**/
                foreach ($data as $key => $value){
                    if($key == "total_amount" || $key == "preferential" || $key == "stay_amount" || $key == "direct_discount"){
                        if($contract_front[$key] == $value * 100){
                            continue;
                        }else{

                            if($key == "course"){    //课程
                                if($value == '' || $value == null){
                                    continue;
                                }
                                $course_name = '';
                                $course_arr = explode(',', $contract_front[$key]);
                                foreach ($course_arr as $v) {
                                    $course_name .= ','.$CourseModel->where('id', $v)->value('course_name');
                                }
                                $contract_front[$key]  = $course_name;
                            }

                            if($key == "discount_rate"){
                                $contract_front[$key] = $contract_front[$key].'%';
                                $value = $value.'%';
                            }

                            if($key == "discount_modle"){
                                if($contract_front[$key] == 1){
                                    $contract_front[$key]  =  "先折扣后直减";
                                }else if($contract_front[$key] == 2){
                                    $contract_front[$key]  =  "先直减后折扣";
                                }

                                if($value == 1){
                                    $value =  "先折扣后直减";
                                }else if($value == 2){
                                    $value =  "先直减后折扣";
                                }
                            }

                            //插入数据库
                            $data_value['change_front'] = $contract_front[$key] / 100; //修改前
                            $data_value['change_after'] = $value; //修改后
                            $data_value['contract_number'] = $contract_front['contract_number']; //订单编号
                            $data_value['student_name'] = $contract_front['student_name']; //学生姓名
                            $data_value['action'] = $key_value[$key].'【修改动作】';  //动作
                            $data_value['contractor'] = $contract_front['contractor']; //签约人
                            $data_value['change_modifier'] = $user['name'];
                            $data_value['campus_id'] = $data['campus_id']; //校区ID
                            ContractModificationModel::create($data_value);  //插入修改记录表
                        }
                    }else if($contract_front[$key] == $value){
                        continue;
                    }else{

                        if($key == "course"){    //课程
                            if($value == '' || $value == null){
                                continue;
                            }
                            $course_name = '';
                            $course_arr = explode(',', $contract_front[$key]);
                            foreach ($course_arr as $v) {
                                $course_name .= ','.$CourseModel->where('id', $v)->value('course_name');
                            }
                            $course_name = substr($course_name,1,strlen($course_name));
                            $contract_front[$key]  = $course_name;



                            $course_name = '';
                            $course_arr = explode(',', $value);
                            foreach ($course_arr as $v) {
                                $course_name .= ','.$CourseModel->where('id', $v)->value('course_name');
                            }
                            $course_name = substr($course_name,1,strlen($course_name));
                            $value  = $course_name;


                        }

                        if($key == "discount_rate"){
                            $contract_front[$key] = $contract_front[$key].'%';
                            $value = $value.'%';
                        }

                        if($key == "discount_modle"){
                            if($contract_front[$key] == 1){
                                $contract_front[$key]  =  "先折扣后直减";
                            }else if($contract_front[$key] == 2){
                                $contract_front[$key]  =  "先直减后折扣";
                            }

                            if($value == 1){
                                $value =  "先折扣后直减";
                            }else if($value == 2){
                                $value =  "先直减后折扣";
                            }
                        }

                        //插入数据库
                        $data_value['change_front'] = $contract_front[$key]; //修改前
                        $data_value['change_after'] = $value; //修改后
                        $data_value['contract_number'] = $contract_front['contract_number']; //订单编号
                        $data_value['student_name'] = $contract_front['student_name']; //学生姓名
                        $data_value['action'] = $key_value[$key].'【修改动作】';  //动作
                        $data_value['contractor'] = $contract_front['contractor']; //签约人
                        $data_value['change_modifier'] = $user['name'];
                        $data_value['campus_id'] = $data['campus_id']; //校区ID
                        ContractModificationModel::create($data_value); //插入修改记录表
                    }
                }
                /***END***/


                $data['total_amount'] = $data['total_amount'] * 100;  //应收
                $data['preferential'] = $data['preferential'] * 100;  //优惠
                $data['stay_amount'] = $data['total_amount']  - $contract_front['amount']; //欠费
                $data['direct_discount'] = $data['direct_discount'] * 100;  //直减优惠

                /**************课程信息更新*********************/
                $CourseContractModel = new CourseContractModel();
                $course_result = $CourseContractModel->where(['contract_id' => $contract_front['id'],'campus_id' => $contract_front['campus_id']])->select();

                $course_id = '';  //课程id
                $course_nums = ''; //课程id对应的数量
                $course_paid_nums = '';  //实交课程ID数
                $course_elimination = ''; //课消



                foreach ($course_result as $key => $value){
                    $course_id = $course_id.$value['course_id'].',';
                    $course_nums = $course_nums.$value['class_num'].',';
                    $course_paid_nums = $course_paid_nums.'0'.',';
                }

                $course_paid_nums = substr($course_paid_nums,0,strlen($course_paid_nums)-1);

                $course_paid_one = 0;

                if(count($course_result) > 0){
                    $price = $course_result[0]['price']; //默认分配到第一个课程
                    $real_rate = ($contract_front['real_rate']/100); //真实的折扣率
                    if($price > 0){
                        $course_paid_one = round(($contract_front['amount'] / ($price*$real_rate)),2);
                    }else{
                        $course_paid_one = 0;
                    }
                }

                $arr = explode(',',$course_paid_nums);
                $arr_num = '';
                for($i =0 ; $i < count($arr); $i ++){
                        if($i == 0){
                            $arr_num = $course_paid_one.',';
                        }else{
                            $arr_num = $arr_num.$arr[$i].',';
                        }
                }


                $arr_num = substr($arr_num,0,strlen($arr_num)-1);

                $course_id = substr($course_id,0,strlen($course_id)-1);
                $course_nums = substr($course_nums,0,strlen($course_nums)-1);


                $course_elimination = $course_nums;

                $data['course'] = $course_id;
                $data['course_nums'] = $course_nums;
                $data['course_paid_nums'] = $arr_num;
                $data['course_elimination'] = $course_elimination;

                if($course_id_str != $data['course']){  //课程信息发生改变
                        //修改前
                        $contract_front_arr = explode(',',$course_id_str);
                        $contract_front_course_arr = '';

                        for ($i=0; $i < count($contract_front_arr); $i ++){
                                $course_name = CourseModel::get(['id' => $contract_front_arr[$i]])['course_name'];
                                $contract_front_course_arr = $contract_front_course_arr.$course_name.'/';
                        }

                        //修改后
                        $contract_after_arr = explode(',',$course_id);
                        $contract_after_course_arr = '';
                        for ($i=0; $i < count($contract_after_arr); $i ++){
                            $course_name = CourseModel::get(['id' => $contract_after_arr[$i]])['course_name'];
                            $contract_after_course_arr = $contract_after_course_arr.$course_name.'/';
                        }


                    //插入数据库
                    $item_value['change_front'] = $contract_front_course_arr; //修改前
                    $item_value['change_after'] = $contract_after_course_arr; //修改后
                    $item_value['contract_number'] = $contract_front['contract_number']; //订单编号
                    $item_value['student_name'] = $contract_front['student_name']; //学生姓名
                    $item_value['action'] = '课程信息'.'【修改动作】';  //动作
                    $item_value['contractor'] = $contract_front['contractor']; //签约人
                    $item_value['change_modifier'] = $user['name'];

                    ContractModificationModel::create($item_value); //插入修改记录表

                }

                if(($contract_front['course'] == $data['course']) && ($contract_front['course_nums'] != $data['course_nums'])){  //课程数量发生改变
                    //修改前
                    $contract_front_nums_course_arr = $contract_front['course_nums'];
                    //修改后
                    $contract_after_nums_arr = $course_nums;



                    //插入数据库
                    $item_value['change_front'] = $contract_front_nums_course_arr; //修改前
                    $item_value['change_after'] = $contract_after_nums_arr; //修改后
                    $item_value['contract_number'] = $contract_front['contract_number']; //订单编号
                    $item_value['student_name'] = $contract_front['student_name']; //学生姓名
                    $item_value['action'] = '课节数量'.'【修改动作】';  //动作
                    $item_value['contractor'] = $contract_front['contractor']; //签约人
                    $item_value['change_modifier'] = $user['name'];

                    ContractModificationModel::create($item_value); //插入修改记录表
                }


                if($data['campus_id'] != $contract_front['campus_id']){  //如果校区改变
                    //更新合同与关系课程表
                    $CourseContractModel->where(['contract_id' => $contract_front['id']])->update(['campus_id' => $data['campus_id']]);
                }

                ContractModel::update($data);
                return ['code' => 0, 'msg' => '修改成功'];
            }
        } catch (\Exception $ex) {
            if(($ex->getCode()) == 10501){
                return ['code' => 1, 'msg' => '数据重复'];
            }
            return ['code' => 1, 'msg' => $ex->getMessage()];
        }
    }
}